package Bank;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class P7Sign {
	public static void main(String[] args) throws Exception {
		if ((args.length < 2) || (args.length > 5)) {
			System.out
					.println("Usage: \nP7Sign keystorefile keystorepassword [inputfile [outputfile]]\n");

			System.exit(-1);
		}
		if ("-debug".equals(args[(args.length - 1)])) {
			PKCS7Tool.setDebug(true);
		}
		PKCS7Tool tool = PKCS7Tool.getSigner(args[0], args[1], args[1]);

		InputStream in = System.in;

		OutputStream out = System.out;
		try {
			if (args.length > 2)
				in = new FileInputStream(args[2]);
			if (args.length > 3) {
				out = new FileOutputStream(args[3]);
			}
			byte[] data = readData(in);

			String signature = tool.sign(data);

			out.write(signature.getBytes());
			System.out.println("[SIGN OK]");
		} finally {
			if ((in != null) && (System.in != in))
				in.close();
			if ((out != null) && (System.out != out))
				out.close();
		}
	}

	private static byte[] readData(InputStream in) throws IOException {
		ByteArrayOutputStream bai = new ByteArrayOutputStream();
		byte[] buf = new byte[256];
		int len;
		while ((len = in.read(buf)) > 0) {
			bai.write(buf, 0, len);
		}
		return bai.toByteArray();
	}
}